import { Component, OnInit, TemplateRef } from '@angular/core';
import { ClassService } from '../../services/class.service';
import { Page } from '../Interfaces/Page';
import { ClassEntity, Search } from '../Interfaces/ClassEntity';

import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { ClassMember, Member, SearchMember } from '../Interfaces/Member';
import { ArrangmentService } from '../../services/arrangment.service';
import { MemberService } from '../../services/member.service';
import { Term } from '../Interfaces/Term';
import { TermService } from '../../services/term.service';


@Component({
  selector: 'app-arrangements',
  templateUrl: './arrangements.component.html',
  styleUrls: ['./arrangements.component.css']
})
export class ArrangementsComponent implements OnInit {

    page: Page;
    rotate = false;
    maxSize = 10;
    memberPage: Page = new Page();
    classEntities: ClassEntity[];
    conditions: Object;
    membersModal: BsModalRef;
    addMemberModal: BsModalRef;
    addClassMemberModal: BsModalRef;
    search: Search = new Search();
    memberSearch: SearchMember = new SearchMember();

    memberList: Member[] = [];
    classMemberList: ClassMember[];
    class_id: number;

    member: Member = new Member();

    // 新增学员用到的变量
    member_class_id: number;  // 新增学员的班级id
    member_term_id: number;   // 新增学员的学期ID
    member_start_time: number;
    member_end_time: number;
    allClassEntities: ClassEntity[];
    allTerms: Term[];

    constructor(
        private modalService: BsModalService,
        private classService: ClassService,
        private memberService: MemberService,
        private termService: TermService,
        private arrangmentService: ArrangmentService,
    ) {
        // this.modalService.onHidden.subscribe(res => { this.getClassEntities(); } );
     }

    ngOnInit() {
        this.conditions = {};
        this.getClassEntities();
        this.getAllTerms();
    }

    getMembers() {
        this.memberService.getMembers().subscribe(res => {
            this.memberList = res.data.data;
            this.memberPage.currentPage = res.data.current_page;
            this.memberPage.total = res.data.total;
            this.memberPage.perPage = res.data.per_page;
        });
    }

    getAllTerms() {
        this.termService.getTerms().then(res => {
            this.allTerms = res as Term[];
        });
    }

    geAllClassEntitiesByTerm() {
        // 默认显示所有班级
        const conditions = new Search();
        if (this.member_term_id) {
            conditions.term_id  = this.member_term_id;
        }
        if (this.member_start_time) {
            conditions.start_time = this.member_start_time;
        }
        if (this.member_end_time) {
            conditions.end_time = this.member_end_time;
        }
        conditions.all = true;
        this.classService.getClassEntitiesByCondition(conditions).subscribe(res => {
            this.allClassEntities  = res.data as ClassEntity[];
        });
    }

    addMember(item: Member) {
        const classMember = new ClassMember();
        classMember.class_id = this.class_id;
        classMember.member_id = item.id;
        classMember.member_name = item.name;
        this.arrangmentService.addClassMember(classMember).subscribe(res => {
            if (!res.errors) { alert('成员加入班级成功'); this.getClassEntities(); } else { alert('添加失败！' + res.message); }
          });
    }

    addMemberItem() {
        // if(this.member.l)
        this.addMemberModal.hide();
        this.memberService.addMember(this.member).subscribe(res => {
            if (!res.errors) {
                alert('添加会员成功');
                this.class_id = this.member_class_id;
                this.member = res.data;
                this.addMember(this.member);
                this.getClassEntities();
            } else { alert('添加失败！'); }
            this.addMemberModal.hide();
        });
    }

    getClassEntities() {
        this.page = new Page();
        this.classService.getClassEntities().subscribe(
            res => {
                this.classEntities = res.data.data as ClassEntity[];
                this.page.currentPage = res.data.current_page;
                this.page.total = res.data.total;
                this.page.perPage = res.data.per_page;
            }
        );
    }



    // 打开查看学员列表窗口
    openShowMembersModal(template: TemplateRef<any>, item: ClassEntity) {
        this.class_id = item.id;
        this.classMemberList = item.members;
        this.membersModal = this.modalService.show(
            template,
            Object.assign({}, {}, { class: 'gray modal-lg' })
        );
    }

    removeMember(item: ClassMember) {
        this.arrangmentService.removeMemberFromClass(item).subscribe(
            res => {
                if (!res.errors) { alert('移除成功'); this.getClassEntities(); } else { alert('移除失败！'); }
            }
        );
    }

    // 新增学员
    openShowAddMemberModal(template: TemplateRef<any>) {
        // 获取所有学期和班级
        this.getAllTerms();

        this.addMemberModal = this.modalService.show(
            template,
            Object.assign({}, {}, { class: 'gray modal-lg' })
        );
        // this.addMemberModal.content.title = '新增学员';
        // this.addMemberModal.content.member = new Member();
    }

    // 添加学员
    openShowAddClassMemberModal(template: TemplateRef<any>, item: ClassEntity) {
        this.class_id = item.id;
        this.getMembers();
        this.addClassMemberModal = this.modalService.show(
            template,
            Object.assign({}, {}, { class: 'gray modal-lg' })
        );
        // console.log(item.id);
    }

    // 条件查询
    searchClassEntity() {
        if (!this.search) {
            return false;
        } else {
            this.arrangmentService.search(this.search).subscribe(res => {
                this.classEntities = res.data.data as ClassEntity[];
                this.page.currentPage = res.data.current_page;
                this.page.total = res.data.total;
                this.page.perPage = res.data.per_page;
            });
        }

    }

    // TODO 分页没做
    pageChanged(event) {
        console.log('Page changed to: ' + event.page);
        console.log('Number items per page: ' + event.itemsPerPage);
        this.search.page = event.page;
        this.searchClassEntity();
    }

    /**弹出框中显示会员列表 */
    searchMember() {
        this.memberService.getMembersByCondition(this.memberSearch).subscribe(
            res => {
                this.memberList = res.data.data as Member[];
                this.memberPage.currentPage = res.data.current_page;
                this.memberPage.total = res.data.total;
                this.memberPage.perPage = res.data.per_page;
            }
        );
        console.log('searchMember');
    }

    /**
     * 关闭查看学员弹窗
     */
    closeShowAddClassMemberModal () {
        this.addClassMemberModal.hide();
        this.memberList = null;
        this.memberPage = new Page();
        this.memberSearch = new SearchMember();
    }

    memberPageChanged(event) {
        console.log('Page changed to: ' + event.page);
        console.log('Number items per page: ' + event.itemsPerPage);
        this.memberSearch.page = event.page;
        this.searchMember();
    }

}


// 新增弹出框
@Component({
    selector: 'app-members-modal',
    template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">{{title}}</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>

    <div class="modal-body">
    <table class="table">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">学员id</th>
            <th scope="col">学员姓名</th>
            <th scope="col">操作</th>
        </tr>
        </thead>
        <tbody *ngIf="list">
            <tr *ngFor="let item of list;index as i; trackBy: trackByFn">
                <th scope="row">{{ i+1 }}</th>
                <td>{{ item.member_id }}</td>
                <td>{{ item.member_name}}</td>
                <td>
                    <button (click)="removeMember(item)" class="btn btn-primary btn-sm" type="button">移除</button>
                </td>
            </tr>
        </tbody>
    </table>
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">关闭</button>
    </div>
    `,
})

export class ClassMemberModalComponent {
    title: string;
    list: Array<ClassMember>;
    class_id: number;

    constructor(
        public bsModalRef: BsModalRef,
        private arrangeService: ArrangmentService,
    ) {

    }

    removeMember(item: ClassMember) {
        this.arrangeService.removeMemberFromClass(item).subscribe(
            res => {
                if (!res.errors) { alert('移除成功'); } else { alert('移除失败！'); }
            }
        );
    }
}


// 新增会员弹出框
@Component({
    selector: 'app-new-modal',
    template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">{{title}}</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>

    <div class="modal-body">
      <form #addForm="ngForm" (submit)="addMember()">
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">会员名称</label>
            <div class="col-sm-9">
                <input type="text"
                *ngIf="member"
                required
                class="form-control"
                name="name"
                [(ngModel)]="member.name"
                placeholder="会员名称"
                #uname="ngModel"
                >
            </div>
        </div>
        <div class="form-group row">
            <label for="phone" class="col-sm-3 col-form-label">联系电话</label>
            <div class="col-sm-9">
                <input type="text"
                *ngIf="member"
                required
                class="form-control"
                name="phone"
                [(ngModel)]="member.phone"
                placeholder="联系电话"
                #uphone="ngModel"
                >
            </div>
        </div>
        <div class="form-group row">
            <label for="age" class="col-sm-3 col-form-label">年龄</label>
            <div class="col-sm-9">
                <input type="number"
                *ngIf="member"
                required
                class="form-control"
                name="age"
                [(ngModel)]="member.age"
                placeholder="年龄请输入数字"
                #uage="ngModel"
                >
            </div>
        </div>

        <div class="form-group row">
            <div class="col-sm-2">
                <button type="submit" [disabled]="!addForm.form.valid" class="btn btn-success" >保存</button>
            </div>
        </div>
      </form>
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">关闭</button>
    </div>
    `,
})

export class MemberAddModalComponent {
    title: string;
    member: Member;

    constructor(
        public bsModalRef: BsModalRef,
        private  memberService: MemberService
    ) {
    }

    addMember() {
        this.memberService.addMember(this.member).subscribe(res => {
            if (!res.errors) { alert('添加成功'); } else { alert('添加失败！' + res.message); }
        });
    }
}

// 新增会员弹出框
@Component({
    selector: 'app-new-class-member-modal',
    template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">{{title}}</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>

    <div class="modal-body">
        <table class="table">
            <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">学员id</th>
                <th scope="col">学员姓名</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <tbody *ngIf="list">
                <tr *ngFor="let item of list;index as i; trackBy: trackByFn">
                    <th scope="row">{{ i+1 }}</th>
                    <td>{{ item.id }}</td>
                    <td>{{ item.name}}</td>
                    <td>
                        <button (click)="addMember(item)" class="btn btn-primary btn-sm" type="button">添加</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">关闭</button>
    </div>
    `,
})

export class ClassMemberAddModalComponent {
    title: string;
    list: Array<Member>;
    class_id: number;

    constructor(
        public bsModalRef: BsModalRef,
        private memberService: MemberService,
        private arrangeService: ArrangmentService
    ) {
        this.getMembers();
    }

    getMembers() {
        this.memberService.getMembers().subscribe(res => {
            this.list = res.data.data as Member[];
        });
    }

    addMember(item: Member) {
        const classMember = new ClassMember();
        classMember.class_id = this.class_id;
        classMember.member_id = item.id;
        classMember.member_name = item.name;
        this.arrangeService.addClassMember(classMember).subscribe(res => {
            if (!res.errors) { alert('添加成功'); } else { alert(res.message); }
          });
    }

}
